package de.homelabs.web.homelabs.controller;

import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Properties;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import de.homelabs.hlmodules.cms.api.menu.service.IHLMenuManager;
import de.homelabs.hlmodules.cms.content.service.HLPageManager;
import de.homelabs.hlmodules.cms.realm.service.HLRealmService;

@Controller("frontController")
public class FrontController {
	final static Logger logger = Logger.getLogger(FrontController.class);

	// @Autowired
	// HLConfigurationManager hlConfigManager;
	@Autowired
	@Qualifier("hlRealmService")
	HLRealmService hlRealmService;

	@Autowired
	@Qualifier("hlPageManager")
	HLPageManager pageManager;

	@Autowired
	IHLMenuManager menuManager;

	public FrontController() {
	}

	@RequestMapping("/*")
	protected ModelAndView handleFrontRequest(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws IOException,
			NamingException {
		// Domain in Domainlist?
		if (!hlRealmService.isDomainSupported(request)) {
			response.getWriter().println(
					"Domain: " + hlRealmService.getNormalizedDomain(request)
							+ " not supported!");
			return null;
		}

		// pageConent with content and pageTitle
		Map<String, Object> pageContent = pageManager.getContentByRequest(
				request.getServletPath(),
				hlRealmService.getNormalizedDomain(request));
		String pageTitle = (String) pageContent.get("pageTitle");

		// TODO: TEXT Parase for custom tags (HTMLEdtitorKit)
		StringBuffer content = new StringBuffer(
				(StringBuffer) pageContent.get("content"));
		// try to find comment
		int commentStart = content.toString().indexOf("<#--");
		if (commentStart > -1) {
			// we have a comment
			int commentEnd = content.toString().indexOf("-->", commentStart);
			if (commentEnd > -1) {
				StringBuffer comment = new StringBuffer(content.toString()
						.substring(commentStart + 4, commentEnd));
				logger.debug(comment.toString());
				Properties props = new Properties();
				props.load(new StringReader(comment.toString()));
				for (Object key : props.keySet()) {
					logger.debug("Key: " + (String) key + ", Value: "
							+ props.get(key));
				}
				if (props.containsKey("title"))
					pageTitle = (String) props.get("title");
				content = content.replace(commentStart, commentEnd + 3, "");

			} else {
				logger.error("No ending Comment Tag found!");
			}
		}
		// add hostname to content
		content.append("<br />ContextPath: " + request.getContextPath());
		content.append("<br />getLocalName: " + request.getLocalName());
		content.append("<br />getPathInfo: " + request.getPathInfo());
		content.append("<br />getServerName: " + request.getServerName());
		content.append("<br />getPathTranslated: "
				+ request.getPathTranslated());
		content.append("<br />getRequestURL: " + request.getRequestURL());

		// TODO: move to service class
		map.addAttribute("content", content);
		map.addAttribute("pageTitle", pageTitle);

		// mainmenu
		map.addAttribute("menu", menuManager.getMainMenu());

		// create view
		return new ModelAndView("maintemplate.html");
	}
}
